package com.bookstore.filter;

import com.sun.org.apache.regexp.internal.RE;
import org.apache.ibatis.session.SqlSession;
import utils.MybatisSessionFactory;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Map;

/**
 * Created by Admin on 2016/9/8.
 */
@WebFilter("/*")
public class TranactionFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        SqlSession sqlSession = null;
        try {
            //1. 获取连接
            sqlSession = MybatisSessionFactory.getSession();
            //2. 把请求转给目标 Servlet
            filterChain.doFilter(servletRequest, servletResponse);
            //3. 提交事务
            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
            sqlSession.rollback();
            resp.sendRedirect(req.getContextPath() + "/error-1.jsp");
        } finally {
            MybatisSessionFactory.closeSession();
        }

    }

    @Override
    public void destroy() {

    }
}
